package com.fyzk.activity.zhifu;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.dialog.SeniorZhuiHaoActivity;
import com.fyzk.activity.lottery.gaopin.AnHuiK3Activity;
import com.fyzk.activity.lottery.gaopin.GD11x5Activity;
import com.fyzk.activity.lottery.gaopin.GDKLSFActivity;
import com.fyzk.activity.lottery.gaopin.GXK3Activity;
import com.fyzk.activity.lottery.gaopin.JLK3Activity;
import com.fyzk.activity.lottery.gaopin.JSK3Activity;
import com.fyzk.activity.lottery.gaopin.KLSFActivity;
import com.fyzk.activity.lottery.gaopin.NXK3Activity;
import com.fyzk.activity.lottery.gaopin.SD11x5Activity;
import com.fyzk.activity.lottery.gaopin.SSCActivity;
import com.fyzk.activity.lottery.gaopin.XJ11x5Activity;
import com.fyzk.activity.lottery.shuzicai.DLTActivity;
import com.fyzk.activity.lottery.shuzicai.FC3DActivity;
import com.fyzk.activity.lottery.shuzicai.PL3Activity;
import com.fyzk.activity.lottery.shuzicai.PL5Activity;
import com.fyzk.activity.lottery.shuzicai.QLCActivity;
import com.fyzk.activity.lottery.shuzicai.QXCActivity;
import com.fyzk.activity.lottery.shuzicai.SSQActivity;
import com.fyzk.activity.lottery.shuzicai.klpk.KLPKActivity;
import com.fyzk.activity.lottery.shuzicai.klpk.KLPKBaseActivity;
import com.fyzk.activity.user.xiangxi.NumLotteryOrderDetailActivity;
import com.fyzk.activity.zhifu.NumLotteryZhiFuAdapter.NumLotteryZhiFuOnClick;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.betcode.BetLotteryInfo;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.tyjc.lottery.R;
import com.fyzk.random.RandomFactory;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.utils.TextStyleUtil;
import com.fyzk.view.ASView;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.ViewCallBack.CountDownInterface;

import java.util.ArrayList;
import java.util.List;

/**
 * 数字彩投注类
 */
public class NumLotteryZhiFuActivity extends BetBaseActivity implements
        NumLotteryZhiFuOnClick, CountDownInterface, ASView.OnValueChangedLisener {

    private final String TAG = this.getClass().getSimpleName();

    private TextView endTime_tv;
    private TextView ziXuan;
    private TextView jiXuan;
    private TextView jiXuan5;

    private ListView listView;
    private NumLotteryZhiFuAdapter adapter;

    private LinearLayout prizeStop_ll;
    private CheckBox isPrizeStop_tv;
    private CheckBox szc_zhifu_zhuijia;
    private TextView senior_zhuiHao;

    private ASView zhuiHao;
    private ASView touBei;

    private List<BetLotteryInfo> infos = new ArrayList<BetLotteryInfo>();
    private BetLotteryInfo betInfor = new BetLotteryInfo();

    public static boolean isZhiFuBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        ViewCallBack.getInstance().AttachCountDownObj(this);
        lotteryId = getIntent().getIntExtra(IntentParamUtils.LOTTERYID, 0);
//        betInfor = (BetLotteryInfo) getIntent().getSerializableExtra("bet");

    }

    @Override
    protected void onResume() {
        super.onResume();
        infos = AppLotteryCodeListManager.getInstance().getList();
        adapterChange();
        isZhiFuBack = false;
        if (infos != null && infos.size() > 0) {
            BetLotteryInfo betInfor1 = infos.get(0);
            betInfor.wcodeID = betInfor1.wcodeID;
            betInfor.codeNum = betInfor1.codeNum;
            betInfor.zhushu = betInfor1.zhushu;
            betInfor.arr_infos = betInfor1.arr_infos;
            betInfor.popupID = betInfor1.popupID;

        } else {
        }
        setSeniorZhuiHaoImg();
    }

    private void setSeniorZhuiHaoImg() {
        Drawable img_Left;
        Resources res = getContext().getResources();
        int img_id;
        if (phases.equals("") || beiShus.equals("")) {
            img_id = R.drawable.btn_xing_no;
            phases = "";
            beiShus = "";
            isGaoJiZhuiHao = false;
        } else {
            isGaoJiZhuiHao = true;
            img_id = R.drawable.btn_xing;
        }
        img_Left = res.getDrawable(img_id);
        img_Left.setBounds(0, 0, img_Left.getMinimumWidth(),
                img_Left.getMinimumHeight());
        senior_zhuiHao.setCompoundDrawables(img_Left, null, null, null);
        setBtmView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == IntentParamUtils.SENIORZHUIHAO && resultCode == 0 && data != null) {

            new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("高级追号成功")
                    .setPositiveButton("查看订单", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            clear();
                            Intent intent;
                            intent = new Intent(getContext(),
                                    NumLotteryOrderDetailActivity.class);
                            intent.putExtra(IntentParamUtils.BETDETAILID, data.getStringExtra(IntentParamUtils.SENIOR_ZHUIHAO_ID));
                            getContext().startActivity(intent);
                            AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
                            finish();
                        }

                    }).setNegativeButton("完成", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    clear();
                    dialog.cancel();
                    setResult(0x6);
                    AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
                    finish();
                }
            }).setCancelable(false).create().show();
        }

    }

    @Override
    protected void clear() {
        // TODO Auto-generated method stub
        if (infos.size() > 0) {
            infos.clear();
        }
    }

    private int oneAmount = 2;


    @Override
    protected View initCenterView() {
        // TODO Auto-generated method stub
        infos = AppLotteryCodeListManager.getInstance().getList();

        View view = LayoutInflater.from(this).inflate(
                R.layout.dj_layout_numzhifu, null);

        // 优惠劵
        LinearLayout coupon_ll = view.findViewById(R.id.zhifu_coupon_ll);
        coupon_ll.addView(couponZhifuView);

        endTime_tv = view.findViewById(R.id.zhifu_endtime_tv);
        ziXuan = view.findViewById(R.id.szc_zhifu_center_zixuan);
        jiXuan = view.findViewById(R.id.szc_zhifu_center_jixuan1);
        jiXuan5 = view.findViewById(R.id.szc_zhifu_center_jixuan5);
        listView = view.findViewById(R.id.szc_zhifu_listview);
        listView.addFooterView(getListFooterView());
        prizeStop_ll = view
                .findViewById(R.id.szc_zhifu_isprizestop_ll);
        isPrizeStop_tv = view
                .findViewById(R.id.szc_zhifu_isprizestop);
        szc_zhifu_zhuijia = view.findViewById(R.id.szc_zhifu_zhuijia);
        senior_zhuiHao = view.findViewById(R.id.szc_zhifu_senior);

        zhuiHao = view
                .findViewById(R.id.szc_zhifu_zhuiqi);
        zhuiHao.setLeftText("追");
        zhuiHao.setRightText("期");
        if (AppLotteryInfos.isGaoPin(lotteryId)) {
            zhuiHao.setMax(100);
        } else {
            zhuiHao.setMax(30);
        }
        zhuiHao.setOnValueChangedLisener(this);


        if (lotteryId == LotteryIDUtils.DLT_LOTTERY_ID_INT) {
            szc_zhifu_zhuijia.setVisibility(View.VISIBLE);
        } else {
            szc_zhifu_zhuijia.setVisibility(View.GONE);
        }

        touBei = view
                .findViewById(R.id.szc_zhifu_beishu);
        touBei.setLeftText("投");
        touBei.setRightText("倍");
        touBei.setOnValueChangedLisener(this);

        isPrizeStop_tv
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        // TODO Auto-generated method stub
                        isPrizeStop = isChecked;
                    }
                });

        szc_zhifu_zhuijia.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    isZhuijia = true;
                    oneAmount = 3;
                } else {
                    oneAmount = 2;
                    isZhuijia = false;
                }
                adapter.setOneAmount(oneAmount);
                adapter.notifyDataSetChanged();
                setBtmView();
            }
        });

        // 高级追号
        senior_zhuiHao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getContext(),
                        SeniorZhuiHaoActivity.class);
                intent.putExtra(IntentParamUtils.LOTTERYID, lotteryId);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_NUM, zhuiQi);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_PRIZESTOP, isPrizeStop);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_ADDITION, isZhuijia);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_BETCODE, getBetCode());
                intent.putExtra(IntentParamUtils.MULTIPLE, getBeishu());
                intent.putExtra(IntentParamUtils.AMT, getAmt());
                if (AppLotteryInfos.isGaoPin(lotteryId)) {
                    intent.putExtra(IntentParamUtils.AMT_MAXZHUI, 100);
                } else {
                    intent.putExtra(IntentParamUtils.AMT_MAXZHUI, 30);
                }
                startActivityForResult(intent,  IntentParamUtils.SENIORZHUIHAO);
            }
        });

        if (adapter == null) {
            adapter = new NumLotteryZhiFuAdapter(getContext(), infos,
                    getOneAmount());
            adapter.setListener(this);
        }
        listView.setAdapter(adapter);
        listView.setItemsCanFocus(false);

        ziXuan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (isMaxPayCount(1)) {
                    return;
                }
                fromZhiFuBack(-1);
            }
        });

        jiXuan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (isMaxPayCount(1)) {
                    return;
                }
                // 机选1注
                if (betInfor != null) {
                    RandomFactory.getRandom(lotteryId).randomYiZhu(betInfor);
                    adapterChange();
                    setBtmView();
                }
            }
        });

        jiXuan5.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (isMaxPayCount(5)) {
                    return;
                }
                if (betInfor != null) {
                    // 机选5注
                    for (int i = 0; i < 5; i++) {
                        RandomFactory.getRandom(lotteryId).randomYiZhu(betInfor);
                    }
                    adapterChange();
                    setBtmView();
                }
            }
        });

        return view;
    }

    private final int maxPayCount = 100;    // 支付列表最大显示条数

    private boolean isMaxPayCount(int addCount) {
        boolean isMax = infos.size() + addCount > maxPayCount;
        if (isMax) {
            AppToast.getToast().show("最多添加" + maxPayCount + "单到号码篮里！");
        }
        return isMax;
    }

    private void fromZhiFuBack(int position) {
        Intent intent;
        switch (lotteryId) {
            case LotteryIDUtils.SSQ_LOTTERY_ID_INT:
                intent = new Intent(getContext(), SSQActivity.class);
                break;
            case LotteryIDUtils.DLT_LOTTERY_ID_INT:
                intent = new Intent(getContext(), DLTActivity.class);
                break;
            case LotteryIDUtils.PL3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), PL3Activity.class);
                break;
            case LotteryIDUtils.PL5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), PL5Activity.class);
                break;
            case LotteryIDUtils.FC3D_LOTTERY_ID_INT:
                intent = new Intent(getContext(), FC3DActivity.class);
                break;
            case LotteryIDUtils.QXC_LOTTERY_ID_INT:
                intent = new Intent(getContext(), QXCActivity.class);
                break;
            case LotteryIDUtils.QLC_LOTTERY_ID_INT:
                intent = new Intent(getContext(), QLCActivity.class);
                break;
            case LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), SD11x5Activity.class);
                break;
            case LotteryIDUtils.CQSSC_LOTTERY_ID_INT:
                intent = new Intent(getContext(), SSCActivity.class);
                break;
//		case LotteryIDUtils.JXSSC_LOTTERY_ID_INT:
//			intent = new Intent(getContext(), JXSSCActivity.class);
//			break;
            case LotteryIDUtils.NXK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), NXK3Activity.class);
                break;
            case LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), AnHuiK3Activity.class);
                break;
            case LotteryIDUtils.GXK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), GXK3Activity.class);
                break;
            case LotteryIDUtils.JSK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), JSK3Activity.class);
                break;
            case LotteryIDUtils.JLK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), JLK3Activity.class);
                break;
            case LotteryIDUtils.GD11XUAN5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), GD11x5Activity.class);
                break;
            case LotteryIDUtils.XJ11XUAN5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), XJ11x5Activity.class);
                break;
            case LotteryIDUtils.KLSF_LOTTERY_ID_INT:
                intent = new Intent(getContext(), KLSFActivity.class);
                break;
            case LotteryIDUtils.GDKLSF_LOTTERY_ID_INT:
                intent = new Intent(getContext(), GDKLSFActivity.class);
                break;
            case LotteryIDUtils.KLPK_LOTTERY_ID_INT:
                intent = new Intent(getContext(), KLPKActivity.class);
                break;
            default:
                intent = null;
                break;
        }
        if (intent != null) {
//            isZhiFuBack = true;
//            intent.putExtra(LotteryBaseActivity.ID, position);
//            startActivity(intent);
            AppLotteryCodeListManager.betType = AppLotteryCodeListManager.ADDCODE;
            finish();
        }
    }

    @Override
    protected void adapterChange() {
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        // adapter.notifyDataSetChanged();
    }


    @Override
    public int getZhushu() {
        // TODO Auto-generated method stub
        int amount = 0;
        for (BetLotteryInfo info : infos) {
            amount += info.zhushu;
        }
        return amount;
    }

    @Override
    public int getOneAmount() {
        // TODO Auto-generated method stub
        return oneAmount;
    }

    @Override
    public String getBetCode() {

        StringBuffer sb = new StringBuffer();
        for (BetLotteryInfo info : infos) {
//            if (info.wcodeID == K3Activity.K3_LOTTERY_SUMZHI_ID_INT) {
//                String firstCode = info.codeNum.charAt(0) + "";
//                if (firstCode.equals("3")) {
//                    sb.append(K3Activity.K3_LOTTERY_SANTONGHAO_ID_INT);//
//                    sb.append("-1,1,1^!");
//                    if (info.codeNum.length() > 1) {
//                        info.codeNum = info.codeNum.substring(2,
//                                info.codeNum.length());
//                    } else {
//                        continue;
//                    }
//                }
//                if (info.codeNum.contains("18")) {
//                    sb.append(K3Activity.K3_LOTTERY_SANTONGHAO_ID_INT);//
//                    sb.append("-6,6,6^!");
//                    if (info.codeNum.equals("18")) {
//                        info.codeNum = "";
//                    } else if (info.codeNum.length() > 1) {
//                        info.codeNum = info.codeNum.substring(0,
//                                info.codeNum.length() - 3);
//                    } else {
//                        continue;
//                    }
//                }
//
//            }
            if (lotteryId == LotteryIDUtils.KLPK_LOTTERY_ID_INT) {  // 快乐扑克
                klpkNum(info, "对子包选", "11");
                klpkNum(info, "豹子包选", "10");
                klpkNum(info, "顺子包选", "09");
                klpkNum(info, "同花顺包选", "08");
                klpkNum(info, "同花包选", "07");
            }

            if (info.codeNum.length() > 0) {
                sb.append(info.wcodeID);// 200302-01,08|07,08|00|02|03^
                sb.append("-");
                sb.append(info.codeNum);
                sb.append("^!");
            }
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    private void klpkNum(BetLotteryInfo info, String showNum, String baoNum) {
        if (info.codeNum.contains(showNum)) {
            if (info.codeNum.equals(showNum)) {
                info.wcodeID = KLPKBaseActivity.KLPK_LOTTERY_ID_BAOXUAN;
                info.codeNum = baoNum;
            } else {
                if (info.codeNum.contains(",") && info.codeNum.split(",").length == 2) {
                    info.wcodeID -= 10;
                }
                info.codeNum = info.codeNum.replaceAll("," + showNum, "^!" + KLPKBaseActivity.KLPK_LOTTERY_ID_BAOXUAN + "-" + baoNum);
            }
        }
    }

    @Override
    public void onClickDelete(int position) {
        // TODO Auto-generated method stub
        infos.remove(position);
        adapterChange();
        setBtmView();
    }

    @Override
    public void onClickChange(int position) {
        // TODO Auto-generated method stub
//		fromZhiFuBack(position);
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.MODIFICATIONCODE;
        AppLotteryCodeListManager.chooseId = position;
        LogUtil.d("xiugai popupId:" + AppLotteryCodeListManager.getInstance().getList().get(position).popupID);
        finish();
    }

    @Override
    public void countDown() {
        String qi = AppLotteryInfos.getPeriod(lotteryId);
        String phase = "距" + qi + "期截止：";
        String endTime = ViewCallBack.getInstance().refreshTimeLeft(
                AppLotteryInfos.getEndTime(lotteryId));
        String str = phase + endTime;
        SpannableString spannableString = new SpannableString(str);
        TextStyleUtil.foreColorSpan(spannableString, Color.RED, phase.length(), str.length());
        endTime_tv.setText(spannableString);
        endTime(lotteryId);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ViewCallBack.getInstance().DettachCountDownObj(this);
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        ViewCallBack.getInstance().DettachCountDownObj(this);
    }

    @Override
    public void onValueChanged(ASView view, int value) {
        switch (view.getId()) {
            case R.id.szc_zhifu_zhuiqi:
                zhuiQi = value;
                break;
            case R.id.szc_zhifu_beishu:
                beishu = value;
                break;
        }
        setBtmView();
    }

    @Override
    public void onBackPressed() {
        if (infos.size() > 0) {
            showBackDialog();
        } else {
            MySharedPreferences.getInstance().setBetCodeBean(lotteryId, infos);
            super.onBackPressed();
        }
    }

    SureDialog backDialog;
    /**
     * 返回对话框
     */
    private void showBackDialog() {

        if (backDialog == null) {
            backDialog = new SureDialog(this, new SureDialog.OnDialogOKCancleClickListener() {

                @Override
                public void onOKClick() {
                    AppToast.getToast().show("已保存，下次进入彩种将自动调出");
                    MySharedPreferences.getInstance().setBetCodeBean(lotteryId, infos);
                    backDialog.dismiss();
                    AppLotteryCodeListManager.betType = AppLotteryCodeListManager.SAVECODE;
                    finish();

                }

                @Override
                public void onCancleClick() {
                    // TODO Auto-generated method stub
                    clear();
                    MySharedPreferences.getInstance().setBetCodeBean(lotteryId, infos);
                    changCi = 0;
                    zhushu = 0;
                    adapterChange();
                    setBtmView();
                    backDialog.dismiss();
                    AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
                    finish();
                }
            }, "", "是否清除本次选号？", "保存", "清除");
        }
        backDialog.show();
    }
}
